import React, { useState, useEffect, useRef } from 'react';
import * as XLSX from 'xlsx';
import {
  Button,
  Input,
  Label,
  Text,
  Spinner,
  Table,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
} from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import { getGrades, getGradesByClassName } from '../mock/gradeData';
import { mockStudents } from '../mock/studentData';
import { mockClasses } from '../mock/classData';

// 成绩接口定义
interface Grade {
  id: number;
  educationStage: string;
  className: string;
  teachingCycle: string;
  examType: string;
  counselor: string;
  lecturer: string;
  teacherId: string;
  teachingProgress: string;
  totalStudents: number;
  courseName: string;
  teacherName: string;
  notCounted?: number;
  failCount?: number;
  directPromotion?: number;
  promotionRate?: number;
  averageScore?: number;
  examSubject?: string;
  writtenExamProportion?: number;
  computerExamProportion?: number;
  interviewProportion?: number;
  passRate?: number;
}

// 学生详细信息接口
export interface StudentDetail {
  studentId: string;
  studentName: string;
  gender: string;
  age: number;
  major: string;
  class: string;
  admissionDate: string;
  address: string;
  phone: string;
  email: string;
  status: string;
}

// 模拟学生详细信息数据
const mockStudentDetails: StudentDetail[] = [
  {
    studentId: '2023001',
    studentName: '张三',
    gender: '男',
    age: 19,
    major: '计算机科学与技术',
    class: '计科1班',
    admissionDate: '2023-09-01',
    address: '北京市海淀区',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    status: '在读'
  },
  {
    studentId: '2023002',
    studentName: '李四',
    gender: '女',
    age: 18,
    major: '软件工程',
    class: '软件1班',
    admissionDate: '2023-09-01',
    address: '上海市浦东新区',
    phone: '13800138002',
    email: 'lisi@example.com',
    status: '在读'
  },
  {
    studentId: '2023003',
    studentName: '王五',
    gender: '男',
    age: 19,
    major: '数据科学',
    class: '数据1班',
    admissionDate: '2023-09-01',
    address: '广州市天河区',
    phone: '13800138003',
    email: 'wangwu@example.com',
    status: '在读'
  }
];

// 模拟获取学生详情的函数
const getStudentDetail = (studentId: string): StudentDetail | undefined => {
  return mockStudentDetails.find(student => student.studentId === studentId);
};

export default function GradeManagementPage() {
  const { session } = useSession();
  // 学生接口定义
  interface Student {
    id: string;
    name: string;
    score: number;
    status: string;
    abnormalStatus?: string;
    remark?: string;
  }

  // 状态定义
  const [grades, setGrades] = useState<Grade[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentGrade, setCurrentGrade] = useState<Grade | null>(null);
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [isDetailsOpen, setIsDetailsOpen] = useState(false);
  const [form, setForm] = useState({
      educationStage: '人工智能学院', // 默认为人工智能学院
      className: '',
      teachingCycle: '',
      examType: '',
      counselor: '',
      lecturer: '',
      teacherId: '',
      teachingProgress: '',
      totalStudents: 0,
      courseName: '',
      teacherName: '',
      notCounted: 0,
      failCount: 0,
      directPromotion: 0,
      promotionRate: 0,
      averageScore: 0,
      examSubject: '',
      writtenExamProportion: 0,
      computerExamProportion: 0,
      interviewProportion: 0
    });
  const [alert, setAlert] = useState('');
  const [showAlert, setShowAlert] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [classNameFilter, setClassNameFilter] = useState('');
  const [students, setStudents] = useState<Student[]>([]);
  // 筛选状态
  const [educationStageFilter, setEducationStageFilter] = useState('');
  const [examTypeFilter, setExamTypeFilter] = useState('');
  const [teachingCycleFilter, setTeachingCycleFilter] = useState('');
  // 批量删除状态
  const [selectedItems, setSelectedItems] = useState<number[]>([]);
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [filteredGrades, setFilteredGrades] = useState<Grade[]>([]);

  // 权限检查 - 临时设置为true以便测试
  const canEdit = true;
  const canDelete = true;
  const canAdd = true;

  useEffect(() => {
    loadGrades();
  }, []);

  // 从mock数据文件中获取成绩
  const loadGrades = async () => {
    setLoading(true);
    try {
      const gradesData = await getGrades();
      setGrades(gradesData);
    } catch (error) {
      console.error('加载成绩列表失败:', error);
      setAlert('加载成绩列表失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 筛选和分页逻辑
  useEffect(() => {
    let result = [...grades];
    
    // 应用筛选条件
    if (searchTerm) {
      result = result.filter(grade => 
        grade.className.includes(searchTerm) || 
        grade.counselor.includes(searchTerm) || 
        grade.lecturer.includes(searchTerm) ||
        grade.courseName.includes(searchTerm)
      );
    }
    
    if (classNameFilter) {
      result = result.filter(grade => grade.className === classNameFilter);
    }
    
    if (educationStageFilter) {
      result = result.filter(grade => grade.educationStage === educationStageFilter);
    }
    
    if (examTypeFilter) {
      result = result.filter(grade => grade.examType === examTypeFilter);
    }
    
    if (teachingCycleFilter) {
      result = result.filter(grade => grade.teachingCycle === teachingCycleFilter);
    }
    
    setFilteredGrades(result);
    // 重置到第一页
    setCurrentPage(1);
  }, [grades, searchTerm, classNameFilter, educationStageFilter, examTypeFilter, teachingCycleFilter]);

  // 获取分页数据
  const getPaginatedData = () => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return filteredGrades.slice(startIndex, endIndex);
  };

  // 处理页码变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 处理每页条数变化
  const handlePageSizeChange = (size: number) => {
    setPageSize(size);
    setCurrentPage(1);
  };

  // 获取总页数
  const totalPages = Math.ceil(filteredGrades.length / pageSize);

  // 获取所有可选的班级名称
  const getClassNames = () => {
    const classNames = [...new Set(grades.map(grade => grade.className))];
    return classNames;
  };

  // 获取所有可选的学段
  const getEducationStages = () => {
    const stages = [...new Set(grades.map(grade => grade.educationStage))];
    return stages;
  };

  // 获取所有可选的考试类型
  const getExamTypes = () => {
    const types = [...new Set(grades.map(grade => grade.examType))];
    return types;
  };

  // 获取所有可选的教学周期
  const getTeachingCycles = () => {
    const cycles = [...new Set(grades.map(grade => grade.teachingCycle))];
    return cycles;
  };

  // 处理全选/取消全选
  const handleSelectAll = () => {
    if (selectedItems.length === getPaginatedData().length) {
      setSelectedItems([]);
    } else {
      setSelectedItems(getPaginatedData().map(item => item.id));
    }
  };

  // 处理单个选择
  const handleSelectItem = (id: number) => {
    setSelectedItems(prev => 
      prev.includes(id) 
        ? prev.filter(itemId => itemId !== id) 
        : [...prev, id]
    );
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedItems.length === 0) {
      setAlert('请先选择要删除的记录');
      setShowAlert(true);
      return;
    }

    if (window.confirm(`确定要删除选中的 ${selectedItems.length} 条记录吗？`)) {
      try {
        // 模拟删除操作
        setGrades(prev => prev.filter(grade => !selectedItems.includes(grade.id)));
        setSelectedItems([]);
        setAlert('删除成功');
        setShowAlert(true);
      } catch (error) {
        console.error('批量删除失败:', error);
        setAlert('删除失败，请重试');
        setShowAlert(true);
      }
    }
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setForm(prev => ({
      ...prev,
      [name]: name === 'score' || name === 'totalStudents' || name === 'notCounted' || name === 'failCount' || name === 'directPromotion' || name === 'promotionRate' || name === 'averageScore' || name === 'writtenExamProportion' || name === 'computerExamProportion' || name === 'interviewProportion' ? parseFloat(value) || 0 : value
    }));
  };

  // 处理班级选择变化，自动填充相关信息
  const handleClassChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const className = e.target.value;
    setForm(prev => ({ ...prev, className }));
    
    // 根据班级自动填充相关信息
    const classInfo = mockClasses.find(cls => cls.className === className);
    if (classInfo) {
      // 获取专业信息 (根据major字段映射)
      const majorMap: Record<number, string> = {
        1: '人工智能',
        2: '软件工程',
        3: '数据科学'
      };
      
      const majorName = majorMap[classInfo.major] || '专业';
      
      // 自动生成教师号 (模拟)
      const teacherId = `T${new Date().getFullYear()}${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`;
      
      setForm(prev => ({
        ...prev,
        counselor: classInfo.counselor,
        lecturer: classInfo.lecturer,
        totalStudents: classInfo.studentCount,
        teachingProgress: `${majorName}${className.charAt(0) === '2' ? className.substring(2, 4) : className.substring(1, 3)}`,
        teacherId: teacherId,
        teacherName: classInfo.lecturer // 默认任课教师为讲师
      }));
      
      // 自动生成课程名称
      const courseName = `${majorName}基础`;
      setForm(prev => ({ ...prev, courseName }));
    }
  };

  // 重置表单
  const resetForm = () => {
    setForm({
      educationStage: '人工智能学院', // 默认为人工智能学院
      className: '',
      teachingCycle: '',
      examType: '',
      counselor: '',
      lecturer: '',
      teacherId: '',
      teachingProgress: '',
      totalStudents: 0,
      courseName: '',
      teacherName: '',
      notCounted: 0,
      failCount: 0,
      directPromotion: 0,
      promotionRate: 0,
      averageScore: 0,
      examSubject: '',
      writtenExamProportion: 0,
      computerExamProportion: 0,
      interviewProportion: 0
    });
  };

  // 打开添加对话框
  const handleAddOpen = () => {
    resetForm();
    setIsAddOpen(true);
  };

  // 打开详情对话框
  const handleDetailsOpen = (grade: Grade) => {
    setCurrentGrade(grade);
    setForm({
      educationStage: grade.educationStage,
      className: grade.className,
      teachingCycle: grade.teachingCycle,
      examType: grade.examType,
      counselor: grade.counselor,
      lecturer: grade.lecturer,
      teacherId: grade.teacherId,
      teachingProgress: grade.teachingProgress,
      totalStudents: grade.totalStudents || 0,
      courseName: grade.courseName,
      teacherName: grade.teacherName,
      notCounted: grade.notCounted || 0,
      failCount: grade.failCount || 0,
      directPromotion: grade.directPromotion || 0,
      promotionRate: grade.promotionRate || 0,
      averageScore: grade.averageScore || 0,
      examSubject: grade.examSubject || '',
      writtenExamProportion: grade.writtenExamProportion || 0,
      computerExamProportion: grade.computerExamProportion || 0,
      interviewProportion: grade.interviewProportion || 0
    });
    
    // 根据班级筛选学生数据
    const filteredStudents = mockStudents.filter(student => grade.className.includes(student.class));
    
    // 如果没有找到对应班级的学生，则使用mockStudentDetails作为备选
    const studentsToUse = filteredStudents.length > 0 ? filteredStudents : mockStudentDetails;
    
    // 确保学生数量与总人数一致
    const adjustedStudentsToUse = studentsToUse.slice(0, grade.totalStudents || studentsToUse.length);
    
    // 转换为学生列表所需的数据结构
    const studentsFromMock = adjustedStudentsToUse.map(student => ({
      id: student.id.toString(),
      name: student.name || student.studentName,
      score: Math.floor(Math.random() * 40) + 60, // 60-100分的随机成绩
      status: '正常',
      abnormalStatus: Math.random() > 0.8 ? '迟到' : undefined,
      remark: Math.random() > 0.9 ? '表现优秀' : undefined
    }));
    
    setStudents(studentsFromMock);
    
    // 自动计算统计数据
    const totalScore = studentsFromMock.reduce((sum, student) => sum + student.score, 0);
    const avgScore = totalScore / studentsFromMock.length;
    const failCount = studentsFromMock.filter(student => student.score < 60).length;
    const promotionCount = studentsFromMock.filter(student => student.score >= 80).length;
    const promotionRate = (promotionCount / studentsFromMock.length) * 100;
    
    // 更新表单中的统计数据
    setForm(prev => ({
      ...prev,
      totalStudents: studentsFromMock.length,
      failCount,
      promotionRate: Number(promotionRate.toFixed(1)),
      averageScore: Number(avgScore.toFixed(1))
    }));
    
    setIsDetailsOpen(true);
  };

  // 处理添加班级成绩
  const handleAdd = async () => {
    try {
      // 在实际项目中，这里应该调用添加成绩的API
      const newGrade: Grade = {
        id: grades.length > 0 ? Math.max(...grades.map(g => g.id)) + 1 : 1,
        educationStage: form.educationStage,
        className: form.className,
        teachingCycle: form.teachingCycle,
        examType: form.examType,
        counselor: form.counselor,
        lecturer: form.lecturer,
        teacherId: form.teacherId,
        teachingProgress: form.teachingProgress,
        totalStudents: form.totalStudents,
        courseName: form.courseName,
        teacherName: form.teacherName
      };
      const updatedGrades = [...grades, newGrade];
      setGrades(updatedGrades);
      setIsAddOpen(false);
      setAlert('添加班级成绩成功');
      setShowAlert(true);
    } catch (error) {
      console.error('添加班级成绩失败:', error);
      setAlert('添加班级成绩失败');
      setShowAlert(true);
    }
  };

  // 处理详情模态框表单提交
  const handleDetailsSubmit = async () => {
    if (!currentGrade) return;
    try {
      // 在实际项目中，这里应该调用更新数据的API
      const updatedGrades = grades.map(grade => 
        grade.id === currentGrade.id ? {
          ...grade,
          educationStage: form.educationStage,
          className: form.className,
          teachingCycle: form.teachingCycle,
          examType: form.examType,
          counselor: form.counselor,
          lecturer: form.lecturer,
          teacherId: form.teacherId,
          teachingProgress: form.teachingProgress,
          totalStudents: form.totalStudents,
          courseName: form.courseName,
          teacherName: form.teacherName,
          notCounted: form.notCounted || 0,
          failCount: form.failCount || 0,
          directPromotion: form.directPromotion || 0,
          promotionRate: form.promotionRate || 0,
          averageScore: form.averageScore || 0,
          examSubject: form.examSubject || '',
          writtenExamProportion: form.writtenExamProportion || 0,
          computerExamProportion: form.computerExamProportion || 0,
          interviewProportion: form.interviewProportion || 0
        } : grade
      );
      setGrades(updatedGrades);
      setIsDetailsOpen(false);
      setAlert('更新班级信息成功');
      setShowAlert(true);
    } catch (error) {
      console.error('更新班级信息失败:', error);
      setAlert('更新班级信息失败');
      setShowAlert(true);
    }
  };

  // 创建隐藏的文件输入元素引用
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 生成并下载学生导入模板
  const handleDownloadTemplate = () => {
    // 创建模板数据
    const templateData = [
      ['学号', '姓名', '综合成绩', '状态', '异常状态', '备注'],
      ['2024001', '示例学生1', 85, '正常', '', ''],
      ['2024002', '示例学生2', 60, '正常', '迟到', ''],
      ['2024003', '示例学生3', 92, '正常', '', '表现优秀']
    ];

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(templateData);
    
    // 设置列宽
    const wscols = [
      { wch: 10 }, // 学号列宽
      { wch: 12 }, // 姓名列宽
      { wch: 10 }, // 综合成绩列宽
      { wch: 8 },  // 状态列宽
      { wch: 10 }, // 异常状态列宽
      { wch: 20 }  // 备注列宽
    ];
    ws['!cols'] = wscols;

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '学生数据');

    // 生成XLSX文件并下载
    XLSX.writeFile(wb, '学生导入模板.xlsx');
  };

  // 处理文件选择并导入学生数据
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const importedStudents: Student[] = [];
        
        // 根据文件扩展名判断处理方式
        if (file.name.endsWith('.csv')) {
          // 处理CSV文件
          const text = e.target?.result as string;
          const lines = text.split('\n');
          if (lines.length < 2) {
            throw new Error('CSV文件格式不正确，至少需要包含标题行和一行数据');
          }

          // 跳过标题行，解析数据行
          for (let i = 1; i < lines.length; i++) {
            const line = lines[i].trim();
            if (!line) continue; // 跳过空行

            const [id, name, scoreStr, status, abnormalStatus, remark] = line.split(',');
            
            // 验证必要字段
            if (!id || !name) continue;

            importedStudents.push({
              id: id.trim(),
              name: name.trim(),
              score: scoreStr ? parseInt(scoreStr.trim()) || 0 : 0,
              status: status?.trim() || '正常',
              abnormalStatus: abnormalStatus?.trim() || undefined,
              remark: remark?.trim() || undefined
            });
          }
        } else if (file.name.endsWith('.xls') || file.name.endsWith('.xlsx')) {
          // 处理Excel文件
          const data = new Uint8Array(e.target?.result as ArrayBuffer);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          
          // 转换为JSON格式
          const jsonData = XLSX.utils.sheet_to_json(worksheet);
          
          if (jsonData.length === 0) {
            throw new Error('Excel文件中没有找到数据');
          }
          
          // 解析数据行
          jsonData.forEach((row: any) => {
            const id = row['学号'] || row['id'] || '';
            const name = row['姓名'] || row['name'] || '';
            
            if (!id || !name) return; // 跳过无效行
            
            importedStudents.push({
              id: String(id).trim(),
              name: String(name).trim(),
              score: row['综合成绩'] || row['score'] || 0,
              status: row['状态'] || row['status'] || '正常',
              abnormalStatus: row['异常状态'] || row['abnormalStatus'] || undefined,
              remark: row['备注'] || row['remark'] || undefined
            });
          });
        } else {
          throw new Error('不支持的文件格式，请上传CSV、XLS或XLSX格式的文件');
        }

        if (importedStudents.length === 0) {
          throw new Error('未从文件中找到有效的学生数据');
        }

        // 更新学生列表
        setStudents(importedStudents);

        // 自动计算统计数据
        const totalScore = importedStudents.reduce((sum, student) => sum + student.score, 0);
        const avgScore = totalScore / importedStudents.length;
        const failCount = importedStudents.filter(student => student.score < 60).length;
        const promotionCount = importedStudents.filter(student => student.score >= 80).length;
        const promotionRate = (promotionCount / importedStudents.length) * 100;
        
        // 更新表单中的统计数据
        setForm(prev => ({
          ...prev,
          totalStudents: importedStudents.length,
          failCount,
          promotionRate: Number(promotionRate.toFixed(1)),
          averageScore: Number(avgScore.toFixed(1))
        }));

        // 保存到localStorage实现持久化
        if (currentGrade) {
          const storageKey = `students_${currentGrade.id}`;
          localStorage.setItem(storageKey, JSON.stringify(importedStudents));
        }

        // 显示导入成功提示
        setAlert(`成功导入${importedStudents.length}名学生数据`);
        setShowAlert(true);
      } catch (error) {
        console.error('导入学生数据失败:', error);
        setAlert(`导入学生数据失败: ${error instanceof Error ? error.message : '未知错误'}`);
        setShowAlert(true);
      }
    };
    reader.onerror = () => {
      setAlert('读取文件失败');
      setShowAlert(true);
    };
    
    // 根据文件类型选择读取方法
    if (file.name.endsWith('.csv')) {
      reader.readAsText(file);
    } else if (file.name.endsWith('.xls') || file.name.endsWith('.xlsx')) {
      reader.readAsArrayBuffer(file);
    } else {
      reader.readAsText(file); // 默认回退到文本读取
    }

    // 重置文件输入，以便相同文件可以再次触发change事件
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 处理学生导入
  const handleStudentImport = () => {
    // 触发隐藏的文件输入元素
    fileInputRef.current?.click();
  };

  // 从localStorage加载学生数据
  useEffect(() => {
    if (currentGrade && isDetailsOpen) {
      const storageKey = `students_${currentGrade.id}`;
      const savedStudents = localStorage.getItem(storageKey);
      if (savedStudents) {
        try {
          const studentsData = JSON.parse(savedStudents);
          setStudents(studentsData);
          
          // 重新计算统计数据
          const totalScore = studentsData.reduce((sum: number, student: Student) => sum + student.score, 0);
          const avgScore = totalScore / studentsData.length;
          const failCount = studentsData.filter((student: Student) => student.score < 60).length;
          const promotionCount = studentsData.filter((student: Student) => student.score >= 80).length;
          const promotionRate = (promotionCount / studentsData.length) * 100;
          
          setForm(prev => ({
            ...prev,
            totalStudents: studentsData.length,
            failCount,
            promotionRate: Number(promotionRate.toFixed(1)),
            averageScore: Number(avgScore.toFixed(1))
          }));
        } catch (error) {
          console.error('加载保存的学生数据失败:', error);
        }
      }
    }
  }, [currentGrade, isDetailsOpen]);

  // 计算班级平均分的平均值
  const averageClassAverageScore = filteredGrades.length > 0 
    ? (filteredGrades.reduce((sum, grade) => sum + grade.averageScore, 0) / filteredGrades.length).toFixed(2) 
    : 0;
  
  // 计算总及格率的平均值
  const averagePassRate = filteredGrades.length > 0 
    ? (filteredGrades.reduce((sum, grade) => sum + (grade.passRate || 0), 0) / filteredGrades.length).toFixed(2) 
    : 0;

  return (
    <div className="p-6 bg-white">
      {/* 页面标题和操作按钮 */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6 gap-4">
        <Text className="text-2xl font-bold text-gray-900">班级成绩管理</Text>
        <div className="flex flex-wrap items-center gap-3">
            <div className="relative">
              <Input
                type="text"
                placeholder="搜索班级、课程名称或教师..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
              <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">🔍</span>
            </div>
            <select
              value={classNameFilter}
              onChange={(e) => setClassNameFilter(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
            >
              <option value="">全部班级</option>
              {getClassNames().map((className) => (
                <option key={className} value={className}>{className}</option>
              ))}
            </select>
            <select
              value={educationStageFilter}
              onChange={(e) => setEducationStageFilter(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
            >
              <option value="">全部学段</option>
              {getEducationStages().map((stage) => (
                <option key={stage} value={stage}>{stage}</option>
              ))}
            </select>
            <select
              value={examTypeFilter}
              onChange={(e) => setExamTypeFilter(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
            >
              <option value="">全部考试类型</option>
              {getExamTypes().map((type) => (
                <option key={type} value={type}>{type}</option>
              ))}
            </select>
            <select
              value={teachingCycleFilter}
              onChange={(e) => setTeachingCycleFilter(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
            >
              <option value="">全部教学周期</option>
              {getTeachingCycles().map((cycle) => (
                <option key={cycle} value={cycle}>{cycle}</option>
              ))}
            </select>
          {canAdd && (
            <Button variant="primary" onClick={handleAddOpen}>
              录入班级成绩
            </Button>
          )}
          {canDelete && selectedItems.length > 0 && (
            <Button variant="destructive" onClick={handleBatchDelete}>
              批量删除 ({selectedItems.length})
            </Button>
          )}
        </div>
      </div>

      {/* 统计信息 */}
      <div className="bg-blue-50 p-4 rounded-md mb-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div className="flex items-center gap-8">
          </div>
        </div>
      </div>

      {/* 警告提示 */}
      {showAlert && (
        <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
          <Text className="text-blue-700">{alert}</Text>
          <Button 
            variant="ghost"
            size="sm" 
            onClick={() => setShowAlert(false)}
            className="absolute right-3 top-2 text-blue-500"
          >
            ×
          </Button>
        </div>
      )}

      {/* 成绩列表表格 */}
      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-16">
                <input 
                  type="checkbox" 
                  checked={selectedItems.length === getPaginatedData().length && getPaginatedData().length > 0} 
                  onChange={handleSelectAll} 
                  className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </TableHead>
              <TableHead>ID</TableHead>
              <TableHead>学段</TableHead>
              <TableHead>班级</TableHead>
              <TableHead>教学周期</TableHead>
              <TableHead>考试类型</TableHead>
              <TableHead>导员</TableHead>
              <TableHead>讲师</TableHead>
              <TableHead>教师号</TableHead>
              <TableHead>教学进度</TableHead>
              <TableHead>课程名称</TableHead>
              <TableHead>总人数</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={13} className="text-center py-8">
                  <Spinner className="mx-auto" />
                </TableCell>
              </TableRow>
            ) : filteredGrades.length === 0 ? (
              <TableRow>
                <TableCell colSpan={13} className="text-center py-8">
                  暂无成绩数据
                </TableCell>
              </TableRow>
            ) : (
              getPaginatedData().map((grade) => (
                <TableRow key={grade.id}>
                  <TableCell>
                    <input 
                      type="checkbox" 
                      checked={selectedItems.includes(grade.id)} 
                      onChange={() => handleSelectItem(grade.id)} 
                      className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                    />
                  </TableCell>
                  <TableCell>{grade.id}</TableCell>
                  <TableCell>{grade.educationStage}</TableCell>
                  <TableCell>{grade.className}</TableCell>
                  <TableCell>{grade.teachingCycle}</TableCell>
                  <TableCell>{grade.examType}</TableCell>
                  <TableCell>{grade.counselor}</TableCell>
                  <TableCell>{grade.lecturer}</TableCell>
                  <TableCell>{grade.teacherId}</TableCell>
                  <TableCell>{grade.teachingProgress}</TableCell>
                  <TableCell>{grade.courseName}</TableCell>
                  <TableCell>{grade.totalStudents}</TableCell>
                  <TableCell>
                    <div className="flex space-x-2">
                      {canEdit && (
                        <Button variant="ghost" onClick={() => handleDetailsOpen(grade)}>
                          详情
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 分页组件 */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mt-4">
        <div className="text-sm text-gray-600 mb-4 md:mb-0">
          共 {filteredGrades.length} 条记录，第 {currentPage} / {totalPages} 页
        </div>
        <div className="flex items-center space-x-2">
          <select
            value={pageSize}
            onChange={(e) => handlePageSizeChange(Number(e.target.value))}
            className="px-2 py-1 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
          >
            <option value={5}>5条/页</option>
            <option value={10}>10条/页</option>
            <option value={20}>20条/页</option>
            <option value={50}>50条/页</option>
          </select>
          <Button
            variant="outline"
            size="sm"
            onClick={() => handlePageChange(1)}
            disabled={currentPage === 1}
          >
            首页
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            上一页
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="sm"
                onClick={() => handlePageChange(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="sm"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            下一页
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => handlePageChange(totalPages)}
            disabled={currentPage === totalPages}
          >
            末页
          </Button>
        </div>
      </div>

      {/* 添加班级成绩对话框 */}
      <Dialog open={isAddOpen} onOpenChange={setIsAddOpen} className="max-w-3xl">
        <DialogContent>
          <DialogHeader>
            <DialogTitle>录入班级成绩</DialogTitle>
            <DialogDescription>
              请填写班级成绩统计信息
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="educationStage" className="text-right">学段</Label>
              <select
                id="educationStage"
                name="educationStage"
                value={form.educationStage}
                onChange={handleInputChange}
                className="col-span-3 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
                required
              >
                <option value="人工智能学院">人工智能学院</option>
                <option value="数据科学学院">数据科学学院</option>
                <option value="软件学院">软件学院</option>
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="className" className="text-right">班级</Label>
              <select
                id="className"
                name="className"
                value={form.className}
                onChange={handleClassChange}
                className="col-span-3 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
                required
              >
                <option value="">请选择班级</option>
                {mockClasses.map((cls) => (
                  <option key={cls.id} value={cls.className}>{cls.className}</option>
                ))}
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="teachingCycle" className="text-right">教学周期</Label>
              <select
                id="teachingCycle"
                name="teachingCycle"
                value={form.teachingCycle}
                onChange={handleInputChange}
                className="col-span-3 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
                required
              >
                <option value="">请选择教学周期</option>
                <option value="2024-2025学年第一学期">2024-2025学年第一学期</option>
                <option value="2024-2025学年第二学期">2024-2025学年第二学期</option>
                <option value="2023-2024学年第一学期">2023-2024学年第一学期</option>
                <option value="2023-2024学年第二学期">2023-2024学年第二学期</option>
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="examType" className="text-right">考试类型</Label>
              <select
                id="examType"
                name="examType"
                value={form.examType}
                onChange={handleInputChange}
                className="col-span-3 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
                required
              >
                <option value="">请选择考试类型</option>
                <option value="月考">月考</option>
                <option value="周考">周考</option>
                <option value="小高考">小高考</option>
                <option value="期中考试">期中考试</option>
                <option value="期末考试">期末考试</option>
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="counselor" className="text-right">导员</Label>
              <Input
                id="counselor"
                name="counselor"
                value={form.counselor}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="lecturer" className="text-right">讲师</Label>
              <Input
                id="lecturer"
                name="lecturer"
                value={form.lecturer}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="teacherId" className="text-right">教师号</Label>
              <Input
                id="teacherId"
                name="teacherId"
                value={form.teacherId}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="teachingProgress" className="text-right">教学进度</Label>
              <Input
                id="teachingProgress"
                name="teachingProgress"
                value={form.teachingProgress}
                onChange={handleInputChange}
                className="col-span-3"
                placeholder="专业X"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="totalStudents" className="text-right">总人数</Label>
              <Input
                id="totalStudents"
                name="totalStudents"
                type="number"
                min="1"
                value={form.totalStudents}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="courseName" className="text-right">课程名称</Label>
              <Input
                id="courseName"
                name="courseName"
                value={form.courseName}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="teacherName" className="text-right">任课教师</Label>
              <Input
                id="teacherName"
                name="teacherName"
                value={form.teacherName}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleAdd}>添加</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 详情模态框 */}
      <Dialog open={isDetailsOpen} onOpenChange={setIsDetailsOpen} className="max-w-4xl">
        <DialogContent>
          <DialogHeader>
            <DialogTitle>班级详情</DialogTitle>
            <DialogDescription>
              查看和修改班级的详细信息
            </DialogDescription>
          </DialogHeader>
          
          {/* 第一个板块：班级列表信息 */}
          <div className="mb-6">
            <h3 className="text-lg font-medium mb-4">班级基本信息</h3>
            <div className="grid gap-4">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="details-teachingCycle">教学周期</Label>
                  <select
                    id="details-teachingCycle"
                    name="teachingCycle"
                    value={form.teachingCycle}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
                  >
                    <option value="">请选择教学周期</option>
                    <option value="2024-2025学年第一学期">2024-2025学年第一学期</option>
                    <option value="2024-2025学年第二学期">2024-2025学年第二学期</option>
                    <option value="2023-2024学年第一学期">2023-2024学年第一学期</option>
                    <option value="2023-2024学年第二学期">2023-2024学年第二学期</option>
                  </select>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-examType">类型</Label>
                  <select
                    id="details-examType"
                    name="examType"
                    value={form.examType}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
                  >
                    <option value="">请选择类型</option>
                    <option value="月考">月考</option>
                    <option value="周考">周考</option>
                    <option value="小高考">小高考</option>
                    <option value="期中考试">期中考试</option>
                    <option value="期末考试">期末考试</option>
                  </select>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-educationStage">学段</Label>
                  <select
                    id="details-educationStage"
                    name="educationStage"
                    value={form.educationStage}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
                  >
                    <option value="">请选择学段</option>
                    <option value="人工智能学院">人工智能学院</option>
                    <option value="数据科学学院">数据科学学院</option>
                    <option value="软件学院">软件学院</option>
                  </select>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-className">班级</Label>
                  <select
                    id="details-className"
                    name="className"
                    value={form.className}
                    onChange={handleClassChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
                  >
                    <option value="">请选择班级</option>
                    {mockClasses.map((cls) => (
                      <option key={cls.id} value={cls.className}>{cls.className}</option>
                    ))}
                  </select>
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="details-counselor">导员</Label>
                  <Input
                    id="details-counselor"
                    name="counselor"
                    value={form.counselor}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-lecturer">讲师</Label>
                  <Input
                    id="details-lecturer"
                    name="lecturer"
                    value={form.lecturer}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-teacherId">教师号</Label>
                  <Input
                    id="details-teacherId"
                    name="teacherId"
                    value={form.teacherId}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="details-teachingProgress">教学进度</Label>
                  <Input
                    id="details-teachingProgress"
                    name="teachingProgress"
                    value={form.teachingProgress}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-courseName">课程</Label>
                  <Input
                    id="details-courseName"
                    name="courseName"
                    value={form.courseName}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-teacherName">任课教师</Label>
                  <Input
                    id="details-teacherName"
                    name="teacherName"
                    value={form.teacherName}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-6 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="details-totalStudents">总人数</Label>
                  <Input
                    id="details-totalStudents"
                    name="totalStudents"
                    type="number"
                    value={form.totalStudents}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-notCounted">不计数</Label>
                  <Input
                    id="details-notCounted"
                    name="notCounted"
                    type="number"
                    value={form.notCounted || 0}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-failCount">不及格</Label>
                  <Input
                    id="details-failCount"
                    name="failCount"
                    type="number"
                    value={form.failCount || 0}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-directPromotion">直升人数</Label>
                  <Input
                    id="details-directPromotion"
                    name="directPromotion"
                    type="number"
                    value={form.directPromotion || 0}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-promotionRate">升班率%</Label>
                  <Input
                    id="details-promotionRate"
                    name="promotionRate"
                    type="number"
                    min="0"
                    max="100"
                    step="0.1"
                    value={form.promotionRate || 0}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-averageScore">平均分</Label>
                  <Input
                    id="details-averageScore"
                    name="averageScore"
                    type="number"
                    min="0"
                    max="100"
                    step="0.1"
                    value={form.averageScore || 0}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
              </div>
            </div>
          </div>
          
          {/* 第二个板块：配置信息 */}
          <div className="mb-6">
            <h3 className="text-lg font-medium mb-4">配置信息</h3>
            <div className="grid gap-4">
              <div className="space-y-2">
                <Label htmlFor="details-examSubject">考试科目</Label>
                <Input
                  id="details-examSubject"
                  name="examSubject"
                  value={form.examSubject || ''}
                  onChange={handleInputChange}
                  className="w-full"
                />
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="details-writtenExamProportion">笔试占比 (%)</Label>
                  <Input
                    id="details-writtenExamProportion"
                    name="writtenExamProportion"
                    type="number"
                    min="0"
                    max="100"
                    step="1"
                    value={form.writtenExamProportion || 0}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-computerExamProportion">机试占比 (%)</Label>
                  <Input
                    id="details-computerExamProportion"
                    name="computerExamProportion"
                    type="number"
                    min="0"
                    max="100"
                    step="1"
                    value={form.computerExamProportion || 0}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="details-interviewProportion">面试占比 (%)</Label>
                  <Input
                    id="details-interviewProportion"
                    name="interviewProportion"
                    type="number"
                    min="0"
                    max="100"
                    step="1"
                    value={form.interviewProportion || 0}
                    onChange={handleInputChange}
                    className="w-full"
                  />
                </div>
              </div>
            </div>
          </div>
          
          {/* 第三个板块：学生列表 */}
          <div>
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-medium">学生列表</h3>
              <div className="flex space-x-2">
                <Button onClick={handleDownloadTemplate} variant="outline">
                  下载模板
                </Button>
                <Button onClick={handleStudentImport}>
                  导入学生
                </Button>
              </div>
            </div>
            
            {/* 隐藏的文件输入元素 */}
            <input
              ref={fileInputRef}
              type="file"
              accept=".csv,.xls,.xlsx"
              onChange={handleFileSelect}
              className="hidden" />
            
            {/* 提示信息 */}
            <div className="text-sm text-gray-500 mb-2">
            
            </div>
            
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>学号</TableHead>
                    <TableHead>姓名</TableHead>
                    <TableHead>综合成绩</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead>异常状态</TableHead>
                    <TableHead>备注</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {students.map((student) => (
                    <TableRow key={student.id}>
                      <TableCell>{student.id}</TableCell>
                      <TableCell>{student.name}</TableCell>
                      <TableCell>{student.score}</TableCell>
                      <TableCell>{student.status}</TableCell>
                      <TableCell>{student.abnormalStatus || '-'}</TableCell>
                      <TableCell>{student.remark || '-'}</TableCell>
                    </TableRow>
                  ))}
                  {students.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={6} className="text-center">暂无学生数据</TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
          
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleDetailsSubmit}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}